<template>
    <!-- 规格选择 -->
    <z-popup closeable title="规格选择" @close="onClose">
        <div class="popup-size">
            <div class="popup-size-main">
                <div class="popup-order-size__group" v-for="groupV,groupK in data.sizeGroup" :key="groupK">
                    <div class="popup-order-size__heading">{{groupV.title}}</div>
                    <ul class="popup-order-size__list">
                        <template v-for="v,k in groupV.sizeList" :key="k">
                            <li :class="{'popup-order-size__item':true, 'active':groupV.active==k}" @click="onCheckSize(groupV, k)" v-if="groupV.type==1">{{v.uomName}}</li>
                            <li :class="{'popup-order-size__item':true, 'active':groupV.active===k}" @click="onCheckSize(groupV, k, groupV.isMultiple)" v-if="groupV.type==2 && groupV.isMultiple==0">{{v.uomName}}</li>
                            <li :class="{'popup-order-size__item':true, 'active':groupV.active.includes(k)}" @click="onCheckSize(groupV, k, groupV.isMultiple)" v-if="groupV.type==2 && groupV.isMultiple==1">{{v.uomName}}</li>
                        </template>
                    </ul>
                </div>
            </div>
            <div class="popup-order-footer">
                <div class="popup-order-footer-selected">已选规格：{{sizeForm.flavor}}</div>
                <div class="popup-order-footer-panel">
                    <div class="popup-order-footer__money">
                        <span class="popup-order-footer__rmb">¥</span>
                        <span class="popup-order-footer__price">{{formatNumber(sizeForm.salePrice)}}</span>
                        <!-- <span class="popup-order-footer__price" style="font-size: 12px;">会员价：{{formatNumber(sizeForm.vipPrice)}}</span> -->
                    </div>
                    <div class="popup-order-footer__control">
                        <stepper 
                            :min="(data.priceList[0].saleLimitMin && numList.length == 0) ? data.priceList[0].saleLimitMin : 1" 
                            v-model="goodsNum" 
                            style="margin-right: 22px;" 
                            :step="data.priceList[0].saleLimitStep"
                            :max="data.priceList[0].saleLimitMax"
                        ></stepper>
                        <!-- priceList -->
                        <!-- <template v-if="numList.every((v) => v.flavor !== sizeForm.flavor)">
                            <z-button @click="onJoinCart" :disabled="isDisabled">加入</z-button>
                        </template> -->
                        <!-- <template v-for="v,k in numList" :key="k">
                            <template v-if="v.flavor==sizeForm.flavor">
                                <stepper 
                                    :min="0" 
                                    v-model="v.totalNum" 
                                    style="margin-right: 22px;" 
                                    v-if="v.totalNum>0"
                                    :step="v.saleLimitStep"
                                    :max="v.saleLimitMax"
                                    @plus="onJoinCart('plus')"
                                    @minus="onJoinCart('minus')"
                                ></stepper>
                            </template>
                        </template> -->
                    </div>
                </div>
                <div class="popup-order-footerBtn">
                    <z-button class="footerBtn" @click="onJoinCart" :disabled="isDisabled">加入</z-button>
                </div>
            </div>
        </div>
    </z-popup>
</template>
<script setup>
import useCartStore from '@/store/cart'
import useSignStore from '@/store/sign'
import { formatNumber } from '@/lib/util.js'
const props = defineProps({
    data: {
        type: Object,
        required: true
    },
    source: {
        type: String,
        default: 'cart'
    },
})

const source = toRef(props, 'source')
const cartStore = unref(source)=='cart'?useCartStore():useSignStore()
const data = toRef(props, 'data')
const sizeForm = ref({})
const sizePrice = ref('')
const isDisabled = ref(false)
const goodsNum = ref(1)
// const isDisabledJoin = ref(false)
console.log(data);

watch(data, (nData) => {
    // console.log('nData')
    console.log(nData)
    let output = {}
    const content = []
    nData.sizeGroup.forEach((v, k) => {
        const list = v.sizeList
        const cur = v.active
        if (v.type == 1) {
            isDisabled.value = list[cur].isEstmClear!=0||list[cur].state!=1?true:false
            // isDisabledJoin.value = list[cur].isDisabledPlus
            output = {
                ...list[cur]
            }
            content.push(list[cur].uomName)
        } else {
            if (v.isMultiple == 0) {
                content.push(list[cur].uomName)
            } else {
                const mArr = cur.map(index => list[index].uomName)
                content.push(mArr.join("、"))
            }
        }
    })
    sizeForm.value = {
        mathType: 'plus',
        type: nData.type,
        num: 1,
        attachment: nData.attachment,
        flavor: content.join("、"),
        goodsType: nData.goodsType,
        groupCode: nData.groupCode,
        ...output,
    }
}, { immediate: true, deep: true })

const numList = ref([])
watch(cartStore.cartList, (cartList) => {

    numList.value = [];
    const priceList = unref(data).priceList
    priceList.forEach((priceItem) => {
        const matchingItems = cartList.filter((cartItem) => cartItem.itemCode === priceItem.itemCode);
        matchingItems.forEach((matchingItem) => {
            const existingItem = unref(numList).find((item) => item.itemCode === matchingItem.itemCode && item.flavor === matchingItem.flavor);
            if (existingItem) {
                existingItem.totalNum += matchingItem.num;
            } else {
                const newItem = {
                    itemCode: matchingItem.itemCode,
                    uomName: priceItem.uomName,
                    isEstmClear: priceItem.isEstmClear,
                    state: priceItem.state,
                    flavor: matchingItem.flavor,
                    totalNum: matchingItem.num,
                    saleLimitMin:priceItem.saleLimitMin,
                    saleLimitStep:priceItem.saleLimitStep,
                    saleLimitMax:priceItem.saleLimitMax
                };
                unref(numList).push(newItem);
            }
        });
    });
    console.log(numList.value);
    
    // console.log(cartList)
    // console.log(unref(numList))
}, { immediate: true })

const emits = defineEmits(['join', 'update:show']);

const onClose = () => {
    emits('update:show', false)
}

const onJoinCart = function(mathType) {
    const form = {
        ...unref(sizeForm),
        mathType:"plus"
    }
    updateFlavor(form)
    console.log(form);
    
    form.num = goodsNum.value
    form.addType = 'size'
    cartStore.RefreshCart(form)
    // console.log(cartStore.cartList)
    // emits('join', sizeForm.value)
    emits('update:show',false)
}
const updateFlavor = (obj)=> {  
    const { flavor, uomName } = obj;
    if(!flavor || !uomName){
        return obj
    }
    // 判断flavor中是否包含uomName
    if (flavor.includes(uomName)) {
    // 删除flavor中的uomName部分并修整字符串，去掉前后的逗号和空格
    obj.flavor = flavor
        .replace(uomName, '') // 删除uomName
        .replace(/、\s*$/, '') // 如果结尾有逗号，去掉
        .replace(/^\s*、/, '') // 如果开头有逗号，去掉
        .trim(); // 删除前后的空格
    }

    return obj;
}

// 选择规格
const onCheckSize = (groupV, k, isMultiple) => {
    console.log(groupV, k, isMultiple);
    
    if (isMultiple == 1) {
        const arr = groupV.active;
        const idx = arr.indexOf(k);
        if (idx !== -1) {
            arr.splice(idx, 1);
        } else {
            arr.push(k);
        }
    } else {
        // console.log(groupV)
        groupV.active = k
    }
}
</script>
<style scoped lang="scss">
.popup-size {
    width: 334px;
    max-height: 600px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    &-main {
        // overflow-y: auto;
        padding: 10px 12px 20px;

        .popup-order-size {

            &__item {
                min-width: 54px;
            }
        }
    }
}
.popup-order-footer{
    padding-bottom: 10px;
    .popup-order-footerBtn{
        display: flex;
        justify-content: flex-end;
        padding: 0 12px;
        .footerBtn{
            // width: 120px;
            flex: 1;
            height: 40px;
        }
        
    }
}

::v-deep{
    .van-stepper__minus, .z-stepper-round .van-stepper__plus {
        background: #FFAA00;
        color: #212121;
    }
    .van-stepper__plus:before{
        background: #212121 !important;
    }
    .van-stepper__plus:after{
        background: #212121 !important;
    }
    .van-stepper__minus, .z-stepper-round .van-stepper__minus {
        background: #FFAA00;
        color: #212121;
    }
    .van-stepper__minus:before{
        background: #212121 !important;
    }
    .van-stepper__minus:after{
        background: #212121 !important;
    }
}

</style>